import { defineComponent, ref } from 'vue';
import modelerStore from '@/store/modules/modeler';
import ElementFactory from 'bpmn-js/lib/features/modeling/ElementFactory';
import Create from 'diagram-js/lib/features/create/Create';
import { NCollapse, NCollapseItem } from 'naive-ui';
import { Collapse, CollapsePanel, Card, Row, Col, Divider } from 'ant-design-vue';
import {
  AuditOutlined,
  SendOutlined,
  ClusterOutlined,
  ContactsOutlined,
  PlusSquareOutlined,
  WalletOutlined,
  MinusCircleOutlined,
  CodepenCircleFilled,
} from '@ant-design/icons-vue';
import { ActiveKeyType } from 'ant-design-vue/es/collapse/commonProps';

const Palette = defineComponent({
  name: 'BpmnPalette',
  setup() {
    const nodeArr = ref([
      {
        title: '人工节点',
        key: 1,
        children: [
          {
            title: '执行节点',
            icon: 'spjd.png',
            event: (e: Event) => createElement(e, 'UserTask', { UserTaskType: 'userTask' }),
          },
          {
            title: '转换节点',
            icon: 'csjd.png',
            event: (e: Event) => createElement(e, 'UserTask', { UserTaskType: 'ccTask' }),
          },
        ],
      },
      {
        title: '分支节点',
        key: 2,
        children: [
          {
            title: '条件分支',
            icon: 'tjfz.png',
            event: (e) => createElement(e, 'ExclusiveGateway', { GatewayType: 'feel' }),
          },
          {
            title: '人工分支',
            icon: 'rgfz.png',
            event: (e: Event) =>
              createElement(e, 'ExclusiveGateway', { GatewayType: 'handSelect' }),
          },
          {
            title: '并行分支',
            icon: 'bxfz.png',
            event: (e) =>
              createElement(e, 'InclusiveGateway', {
                GatewayType: 'InclusiveGateway',
                icon: '/src/assets/bpmnIcon/parallel-gateway.svg',
              }),
          },
        ],
      },
      {
        title: '子流程节点',
        key: 3,
        children: [
          {
            title: '子流程',
            icon: 'zlc.png',
            event: (e) => createElement(e, 'ReceiveTask'),
          },
        ],
      },
      {
        title: '高级节点',
        key: 4,
        children: [
          {
            title: '机器节点',
            icon: 'jqjd.png',
            event: (e) => createElement(e, 'ServiceTask'),
          },
          {
            title: '空结束',
            icon: 'kjs.png',
            event: (e) => createElement(e, 'EndEvent'),
          },
        ],
      },
    ]);
    const allPanelsKey = ref<ActiveKeyType>([1, 2, 3, 4]);
    const store = modelerStore();
    const changeCollapse = (key: ActiveKeyType) => {
      //如果是空数组，则全部展开
      if (key.length === 0) {
        allPanelsKey.value = [1, 2, 3, 4];
      } else {
        allPanelsKey.value = key;
      }
    };
    const createElement = (ev: Event, type: string, options?: any) => {
      //并行网关时，同时创建两个
      if (type === 'ParallelGateway' || type === 'InclusiveGateway') {
        const elementFactory = store.getModeler!.get('elementFactory');
        const modeling = store.getModeler!.get('modeling');
        const canvas = store.getModeler!.get('canvas');
        const parentElement = canvas.getRootElement();

        //创建第一个并行网关
        const gateway1 = elementFactory.createShape({
          type: 'bpmn:InclusiveGateway',
          x: 100,
          y: 100,
        });
        //修改icon，暂时不行
        if (options) {
          const newOptions = { icon: '/assets/bpmnIcon/parallel-gateway.svg', ...options };
          gateway1.businessObject.extended = newOptions;
        }

        modeling.createShape(gateway1, { x: 100, y: 100 }, parentElement);

        //创建第二个并行网关
        const gateway2 = elementFactory.createShape({
          type: 'bpmn:InclusiveGateway',
          x: 300,
          y: 100,
        });

        if (options) {
          gateway2.businessObject.extended = { GatewayType: 'JoinGateway' };
        }
        modeling.createShape(gateway2, { x: 300, y: 100 }, parentElement);
      }
      else {
        const ElementFactory: ElementFactory = store.getModeler!.get('elementFactory');
        const create: Create = store.getModeler!.get('create');
        const shape = ElementFactory.createShape({ type: `bpmn:${type}`, ...{} });
        //修改icon，暂时不行
        if (options) {
          const newOptions = { icon: '/assets/bpmnIcon/parallel-gateway.svg', ...options };
          shape.businessObject.extended = newOptions;
        }
        //如果是服务节点
        if (type === 'ServiceTask') {
          shape.businessObject['activiti:class'] =
            'com.zsix.system.service.listener.MachineService';
          shape.businessObject.$attrs['activiti:class'] =
            'com.zsix.system.service.listener.MachineService';
        }
        create.start(ev, shape);
      }
    };
    const getAssetsFile = (fileName: string) => {
      return new URL(`/src/assets/icons/${fileName}`, import.meta.url).href;
    }
    return () => (
      <div class="palette" style="width:160px">
        <Collapse
          onChange={(key) => changeCollapse(key)}
          activeKey={allPanelsKey.value}
          ghost
          collapsible="header"
          bordered={false}
        >
          {nodeArr.value.map((item) => {
            return (
              <CollapsePanel key={item.key} header={item.title}>
                <Row justify="space-between" wrap>
                  {item.children?.map((child) => (
                    <Col
                      span={24}
                      key={child.key}
                      style={{ backgroundColor: '#F5F6F7', margin: '6px 0' }}
                    >
                      <Card
                        bodyStyle={{
                          padding: '0',
                          textAlign: 'center',
                          background: '#F5F6F7',
                          borderRadius: '4px',
                        }}
                        draggable="true"
                        onDragstart={child.event}
                      >
                        <span color="#222222">
                          <img style={{ width: '14px', height: '14px', marginRight: '6px' }} src={getAssetsFile(child.icon)} />
                          {child.title}
                        </span>
                      </Card>
                    </Col>
                  ))}
                </Row>
              </CollapsePanel>
            );
          })}
        </Collapse>
      </div>
    );
  },
});

export default Palette;
